//
// Created by 11510 on 2024/7/11.
//

#ifndef REDIS_DEMO_REDIS_H
#define REDIS_DEMO_REDIS_H

#include <string>
#include <hiredis/hiredis.h>

class Redis {
private:
    redisContext *_pConnect;
    redisReply *_pReply;
public:
    Redis() : _pConnect(NULL), _pReply(NULL) {}

    ~Redis() {
        if (_pConnect) {
            redisFree(_pConnect);
            _pConnect = NULL;
        }
        if (_pReply) {
            freeReplyObject(_pReply);
            _pReply = NULL;
        }
    }

    bool connect(const std::string &host, int port) {
        _pConnect = redisConnect(host.c_str(), port);
        if (_pConnect == NULL) {
            return false;
        }

        if (_pConnect != NULL && _pConnect->err) {
            perror("connect redis error");
            return false;
        }

        return true;
    }

    void auth(std::string password){
        _pReply = (redisReply *)redisCommand(_pConnect, "auth %s", password.c_str());
        if (_pReply->type == REDIS_REPLY_ERROR) {
            perror("Authentication failed:");
        }
        freeReplyObject(_pReply);
    }

    void set(std::string key, std::string value) {
        _pReply = (redisReply *) redisCommand(_pConnect, "set %s %s", key.c_str(), value.c_str());
        if (_pReply) {
            freeReplyObject(_pReply);
            _pReply = NULL;
        }
    }

    std::string get(std::string key) {
        _pReply = (redisReply *) redisCommand(_pConnect, "get %s", key.c_str());
        if (_pReply && _pReply->type == REDIS_REPLY_STRING) {
            std::string str = _pReply->str;
            freeReplyObject(_pReply);
            _pReply = NULL;
            return str;
        }
        return NULL;

    }
};


#endif //REDIS_DEMO_REDIS_H
